<template>
  <!-- 市场数据 -->
  <el-table
    :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    height="360"
  >
    <el-table-column type="index" label="序号" width="150%" />
    <el-table-column prop="name" label="商品名称">碳配额商品</el-table-column>
    <el-table-column prop="residualAmount" label="余量" />
    <el-table-column prop="listingAmount" label="总量" />
    <el-table-column prop="listingPrice" label="标价" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button link type="primary" @click="Buy(scope.row)">买入</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    background
    layout="prev, pager, next"
    :page-count="totalPage"
    @change="doPageChange"
  />
  <!-- 数据整合 -->
  <el-row :gutter="16">
    <el-col :span="8">
      <v-chart :option="option"></v-chart>
    </el-col>
    <!-- 总交易额 -->
    <el-col :span="8">
      <div class="statistic-card">
        <el-statistic :value="12641">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              碳交易总额
              <el-tooltip effect="dark" content="今日碳排放量交易总额（万元）" placement="top">
                <el-icon style="margin-left: 4px" :size="12">
                  <Warning />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-statistic>
        <div class="statistic-footer">
          <div class="footer-item">
            <span>相比昨日</span>
            <span class="red">
              12%
              <el-icon>
                <CaretBottom />
              </el-icon>
            </span>
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="8">
      <div class="statistic-card">
        <el-statistic :value="72000" title="New transactions today">
          <template #title>
            <div style="display: inline-flex; align-items: center">New transactions today</div>
          </template>
        </el-statistic>
        <div class="statistic-footer">
          <div class="footer-item">
            <span>than yesterday</span>
            <span class="green">
              16%
              <el-icon>
                <CaretTop />
              </el-icon>
            </span>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { CaretBottom, Warning } from '@element-plus/icons-vue'
import { ListingInfoControllerService, TradeControllerService } from '../../../generated'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { quotaShare, transferCarbonCoin } from '@/utils/useWeb3'

const wallet = reactive(JSON.parse(localStorage.getItem('wallet') as string) || {})
const account = ref('0xeE25c9B1863C976867DcfEe90e76b2daB9756504') //ref(wallet.address ? wallet.address : '')
const queryParam = ref({
  pageSize: 8,
  current: 0
})
const totalPage = ref(10)
// 分页设置
const pageSize = 8
const currentPage = ref(1)
// 市场信息
const tableData = ref([])

// 数据图表
const option = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'line'
    }
  ]
}

const loadData = async () => {
  const res = await ListingInfoControllerService.listListingInfoByPageUsingPost(queryParam.value)
  if (res.code === 0) {
    tableData.value = res.data.records
    totalPage.value = Math.floor(
      (Number(queryParam.value.pageSize - 1) + Number(res.data.total)) /
        Number(queryParam.value.pageSize)
    )
  }
}
onMounted(async () => {
  await loadData()
  console.log(tableData.value)
})
/**
 * 分页请求
 * @param page
 */
const doPageChange = (page: any) => {
  queryParam.value.current = page
  loadData()
}

// 买入
const Buy = async (item: any) => {
  const blockchainId = ref()
  // account.value='0xeE25c9B1863C976867DcfEe90e76b2daB9756504'
  //1.扣钱 item.listingPrice
  const res = await transferCarbonCoin(account.value, item.sellerAddress, item.listingPrice)
  blockchainId.value = res.blockchainId
  //2.配额转移 item.residualAmount
  const res2 = await quotaShare(item.sellerAddress, account.value, item.residualAmount)
  //3.删除本次交易商品 item.id
  const res3 = await ListingInfoControllerService.deleteByIdUsingPost({ id: item.id, isDelete: 1 })
  //4.添加交易记录 account item.sellerAddress
  const trade = {
    blockchainId: blockchainId.value ? blockchainId.value : 0,
    amount: item.residualAmount,
    price: item.listingPrice,
    companyId: item.companyId
  }
  const res4 = await TradeControllerService.addTradeUsingPost(trade)

  if (res3.code !== 0 || res4.code !== 0) {
    ElMessage({
      message: '交易失败-数据库异常',
      type: 'error'
    })
    //todo 回溯
  } else {
    if (res.status != 0 || res2.status != 0) {
      ElMessage({
        message: '交易失败-区块链异常',
        type: 'error'
      })
    } else {
      ElMessage({
        message: '交易成功',
        type: 'success'
      })
    }
  }
}
</script>
<style type="scss" scoped>
:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
}

.statistic-card {
  height: 100%;
  padding: 20px;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 16px;
}

.statistic-footer .footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-footer .footer-item span:last-child {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.green {
  color: var(--el-color-success);
}

.red {
  color: var(--el-color-error);
}
</style>
